(function(angular) {
	'use strict';
	var dependencies = [ 'fs.storage', 'fs.logger', 'fs.router', 'fs.menu', 'fs.validation', 'fs.layout', 'fs.modal', 'oc.lazyLoad', 'ngAnimate',
			'ngResource', 'pascalprecht.translate', 'ui.bootstrap', 'cfp.hotkeys', 'angularFileUpload', 'ui.bootstrap.contextMenu',
			'colorpicker.module', 'angular-clipboard', 'chart.js',
			'ui.grid','ui.grid.autoResize','ui.grid.moveColumns','ui.grid.pagination','ui.grid.resizeColumns','ui.grid.selection','ui.grid.treeBase',
			'ui.grid.treeView','ui.grid.cellNav','ui.grid.emptyBaseLayer','ui.grid.expandable','ui.grid.exporter', 'ui.grid.grouping'];
	angular.module("fs.waf", dependencies).controller("mainController", mainController)
	/*.animation(".fade-in", [ "$animateCss", function($animateCss) {
		return {
			enter : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 0
					},
					to : {
						opacity : 1
					},
					duration : 3
				});
			}
		};
	} ])
	.animation(".fade-out", [ "$animateCss", function($animateCss) {
		return {

			leave : function(element) {
				return $animateCss(element, {
					from : {
						opacity : 1
					},
					to : {
						opacity : 0
					},
					duration : 3
				});
			}
		};
	} ])*/;

	mainController.$inject = [ '$rootScope', '$scope', '$log', '$translate', '$locale', '$location', '$q', 'Constants', 'ajaxServiceFactory', 'storageService',
			'signonService', '$ocLazyLoad', 'routerService', 'commonService' ];
	function mainController($rootScope, $scope, $log, $translate, $locale, $location, $q, Constants, ajaxServiceFactory, storageService, signonService, $ocLazyLoad,
			routerService, commonService) {
		var watcher, ctrl = this, log = $scope.loggerFactory.getLogger("mainController");
		ctrl.$onInit = function() {
			initApplicationSetting();
			signonService.isAuthenticated().then(
					function() {
						$rootScope.user = storageService.getUserInfo();
						$rootScope.site = storageService.getSiteInfo();
						$rootScope.menus = storageService.getMenuInfo();
						$rootScope.updateTheme();
						$rootScope.initLocaleData();
						$rootScope.initNotificationData();
						$ocLazyLoad.load(
								[ 'waf/css/' + $scope.app.settings.theme + '/app.css',
								  'waf/js/' + $scope.app.settings.theme + '/test/testRouter.js',
								  'cda/js/' + $scope.app.settings.theme + '/router/pageRouter.js',
								  'cda/js/' + $scope.app.settings.theme + '/router/lookupRouter.js',
								  'cda/js/' + $scope.app.settings.theme + '/router/popupRouter.js',
								  'cda/js/' + $scope.app.settings.theme + '/test/testRouter.js',
								  'cls/js/' + $scope.app.settings.theme + '/router/pageRouter.js',
								  'cls/js/' + $scope.app.settings.theme + '/router/lookupRouter.js',
								  'cls/js/' + $scope.app.settings.theme + '/router/popupRouter.js',
								  'apf/js/' + $scope.app.settings.theme + '/router/pageRouter.js',
								  'apf/js/' + $scope.app.settings.theme + '/router/lookupRouter.js',
								  'apf/js/' + $scope.app.settings.theme + '/router/popupRouter.js',
								  'lfe/js/' + $scope.app.settings.theme + '/router/pageRouter.js',
								  'lfe/js/' + $scope.app.settings.theme + '/router/lookupRouter.js',
								  'lfe/js/' + $scope.app.settings.theme + '/router/popupRouter.js']
								, {
									cache : true
								}
						).then(function() {
							if ($location.state()) {
								$scope.go($location.state());
							} else if($location.url()) {
								$scope.go($location.url().substr(1).split('/').join('.'));
							} else {
								$scope.go(Constants.WELCOME_URL);
							}
						}, function(error) {
							log.error(error);
						});
					},
					function() {
						$ocLazyLoad.load(
								[ 'waf/css/' + $scope.app.settings.theme + '/app.css'], {
									cache : true
								}).then(function() {
									$scope.go('signon');
								}, function(error) {
									log.error(error);
								});
					});
		};
		
		$scope.toggleUserbarDropdown = function($event, item, callback) {
			if (!callback) {
				item.open = !item.open;
				if (item.open) {
					$scope.isUserBarOpen = item.itemCode;
				}
				$event.preventDefault();
				$event.stopPropagation();
			} else {
				if (callback && angular.isString(callback)) {
					callback = ($scope).$eval(callback);
				}
				$scope.isUserBarOpen = false;
				callback(item, $event);
			}
		};
		$scope.userBarOpen = function(item) {
			if ($scope.isUserBarOpen && $scope.isUserBarOpen == item.itemCode) {
				// open is true, will show this menu sub datas
			} else {
				item.open = false;// other sub datas donot show
			}
			return item.open;
		};
		$scope.userBarOpenClick = function() {
			// user sub menu
			if (!$scope.userbarSubMenu) $scope.userbarSubMenu = {};
			if (!$scope.userbarSubMenu.menuStyle) {
				$scope.userbarSubMenu.menuStyle = {
					"itemCode" : "MenuStyle",
					"displayName" : "Menu Style",
					"subMenu": {
						"callback" : "setMenuStyle",
						"data" : {'false': 'Top','true' : 'Left'}
					}
				};
			}
			if (!$scope.userbarSubMenu.logout) {
				$scope.userbarSubMenu.logout = {
					"displayName" : "logout",
					"callback" : "mainCtrl.exit"
				};
			}
			$scope.isUserBarOpen = false;
		};
		
		$scope.setMenuStyle = function(isLeft, $event) {
			$scope.app.settings.leftMenu = isLeft == 'true' ? true : false;
		}
		
		ctrl.exit = function() {
			signonService.exit().then(function() {
				log.debug('had signoff');
				$scope.go('signon');
			}, angular.noop);
		};

		watcher = $rootScope.$watch('app', function(settings) {
			storageService.saveSystemSettings(settings);
		}, true);

		$rootScope.$on('$destroy', function() {
			(watcher || angular.noop)();
		});

		function initApplicationSetting() {
			var defaultApp = {
				color : {},
				settings : {
					theme : Constants.THEME_DEFAULT,
					leftMenu : false,
					logLevel : $log.logLevels['*'],
					collapseLeftMenu : false,
					collapseRightAside : false
				}
			};
			$rootScope.app = angular.merge(defaultApp, storageService.getSystemSettings());
		}
		
		$rootScope.initLocaleData = function() {
			var defer = $q.defer();
			var userLocalesAjaxService = ajaxServiceFactory.buildAjaxService({
				getUserLocales : {
					url : 'do/user/locales',
					method : 'get'
				}
			});
			userLocalesAjaxService.getUserLocales().then(function(response) {
				var language = storageService.getCookie('wafLocale') || $translate.resolveClientLocale() || $translate.proposedLanguage() || storageService.getUserInfo().locale || 'en_US';
				$scope.langs = {};
				angular.forEach(response.data, function(userAttribute, index) {
					$scope.langs[userAttribute.uid] = userAttribute.name;
				});
				$scope.I18N.language = $scope.langs[language] ? language : 'en_US';
				storageService.setCookie('wafLocale', language, 30, false);
				$scope.selectLang = $scope.langs[language] || "English";
				if (!$scope.userbarSubMenu) $scope.userbarSubMenu = {};
				if (!$scope.userbarSubMenu.langMenu) {
					// user sub menu
					$scope.userbarSubMenu.langMenu = {
						"itemCode" : "LocalChange",
						"displayName" : "",
						"subMenu": {
							"callback" : "setLang",
							"data" : {}
						}
					};
				}
				$scope.userbarSubMenu.langMenu.displayName = $scope.selectLang;
				$scope.userbarSubMenu.langMenu.subMenu.data = $scope.langs;
				// change page locale
				$scope.setLang = function(language, $event) {
					if ($scope.selectLang != $scope.langs[language]) {
						$scope.selectLang = $scope.langs[language];
						$scope.userbarSubMenu.langMenu.displayName = $scope.selectLang;
						$scope.userbarSubMenu.langMenu.subMenu.data = $scope.langs;
						// java session
						var changeLocaleAjaxService = ajaxServiceFactory.buildAjaxService({
							changeLocale : {
								url : 'do/user/locale/' + language,
								method : 'get'
							}
						});
						changeLocaleAjaxService.changeLocale().then(function(response) {
							var stateName = $scope.$state.current.name;
							if (stateName) {
								var url = stateName.split('_');
								if (url.length > 2) {
									var module = url[0];
									url = url.slice(-2);
									url = 'do/' + module + '/resource/' + url.join('/');
								} else if (stateName == 'app_waf_home') {
									url = 'do/waf/resource/common/home';
								}
								var loadResourceAjaxService = ajaxServiceFactory.buildAjaxService({
									loadConfig : {
										'url' : url,
										'method' : 'get'
									}
								});
								loadResourceAjaxService.loadConfig().then(function(response) {
									var resources = response ? response.data : null;
									storageService.setCookie('wafLocale', language, 30, false);
									storageService.setItemToSession(Constants.SESSION_I18N_RESOURES, resources);
									storageService.setItemToSession(Constants.SESSION_I18N_VALIDATION_RESOURES, {});
									$rootScope.$emit(Constants.NOTIFY_CHANGE_LANGUAGE, {
										'language' : language
									});
								});
							}
						});
					}
				};
				defer.resolve();
			}); 
			return defer.promise;
		}

		
		/**
		 * $scope.notifications = [ {
				message : 'Notifications One',
				time : '2017/02/20 15:22:30',
			}, {
				message : 'Notifications Two',
				time : '2017/02/20 15:22:30',
			}, {
				message : 'Notifications Three',
				time : '2017/02/20 15:22:30',
			} ];
		 */
		$rootScope.initNotificationData = function() {
			var defer = $q.defer();
			var notificationsAjaxService = ajaxServiceFactory.buildAjaxService({
				getNotifications : {
					url : 'do/cda/deliMessage/notifications',
					method : 'get'
				}
			});
			notificationsAjaxService.getNotifications().then(function(response) {
				$scope.notificationWrap = {};
				$scope.notificationWrap.allNum = response.data.allNum;
				$scope.notificationWrap.notifications = response.data.msgData;
				defer.resolve();
			}); 
			return defer.promise;
		}
		$scope.notificationItemRedirect = function(notification) {
			$scope.go('cda.deliMessage.view', {deliMessageId : notification.deliMessageId, deliveryFolder : 'R'});
		}
		$scope.notificationListRedirect = function() {
			$scope.go('cda.deliMessage.list');
		}

		$rootScope.updateTheme = function() {
			var siteInfo = storageService.getSiteInfo();
			var theme = siteInfo ? (siteInfo.theme || $rootScope.app.settings.theme) : $rootScope.app.settings.theme;
			routerService.setTheme(theme);
			updateLogo();
		}
		function updateLogo() {
			commonService.getLogo().then(function(response) {
				$rootScope.logo = response;
			});
		};
		$rootScope.auditAndNoteButtons = [ {
			"name" : "audit",
			"enabled" : "!disabledAuditOrNote",
			"tooltip" : "label.audit.viewaudit",
			"type" : "button",
			"btnClass" : "btn-default",
			"options" : {
				"icon" : "audit",
				"callback" : {
					"click" : "viewAudit"
				}
			},
			'btnScope' : $scope
		}, {
			"name" : "note",
			"enabled" : "!disabledAuditOrNote",
			"tooltip" : "label.note.create",
			"type" : "button",
			"btnClass" : "btn-default",
			"options" : {
				"icon" : "note",
				"callback" : {
					"click" : "createNote"
				}
			},
			'btnScope' : $scope
		} ];
	}
})(angular);
